package com.rimi.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chengliang
 * 创建时间 2020/3/24 11:46
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //检查该用户是否已经登录
        //从Session中读取当前用户的信息
        //向下类型转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Object user = request.getSession().getAttribute("user");
        //未登录，则重定向到登录页面
        if(user == null){
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendRedirect("/index.jsp");
            return;
        }
        //登录, 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
